package com.dabao.query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * Created by dabao on 16/3/2.
 * 查询的抽象类
 * orderColumn 排序时order by 的 table column
 * isDesc 是否desc排序默认是asc isDesc != null 则为desc
 * page 查询时limit 选项
 */
public abstract class BaseQuery {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String orderColumn;

    private Integer isDesc;

    private Page page;

    public String getOrderColumn() {
        return orderColumn;
    }

    public void setOrderColumn(String orderColumn) {
        this.orderColumn = orderColumn;
    }

    public Integer getIsDesc() {
        return isDesc;
    }

    public void setIsDesc(Integer isDesc) {
        this.isDesc = isDesc;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }

    /**
     * 将查询的参数转化为name1=value1&name2=value2的字符串形式
     * @return
     */
    public String toParams() {
        Field[] fields = this.getClass().getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object obj = field.get(this);
                if(obj != null) {
                    sb.append(field.getName());
                    sb.append("=");
                    sb.append(obj.toString());
                    sb.append("&");
                }
            } catch (IllegalAccessException e) {
                logger.error("获取field value 失败", e);
            }
        }

        if(sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }
}
